package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
)

/**
官方自带reverseproxy 简单实现

*/
var addr = "127.0.0.1:2002"

func main() {
	/**
	http://127.0.0.1:2002/xxx
	http://127.0.0.1:2003/base/xxx
	*/
	rs1 := "http://127.0.0.1:2003/base"
	url, err := url.Parse(rs1)
	if err != nil {
		log.Println(err)
	}

	modifyFunc := func(resp *http.Response) error {
		if resp.StatusCode != http.StatusOK {
			// 获取内容
			oldPayload, err := ioutil.ReadAll(resp.Body)
			if err != nil {
				return err
			}
			newPayload := []byte("hello " + string(oldPayload))
			resp.Body = ioutil.NopCloser(bytes.NewBuffer(newPayload))
			resp.ContentLength = int64(len(newPayload))
			resp.Header.Set("Content-Length", fmt.Sprint(len(newPayload)))
		}
		return nil
	}

	proxy := httputil.NewSingleHostReverseProxy(url)
	proxy.ModifyResponse = modifyFunc
	log.Println("Starting httpserver at " + addr)
	log.Fatal(http.ListenAndServe(addr, proxy))

}
